import React, { useMemo, useState } from 'react';
import {
  Card,
  Statistic,
  Space,
  Button,
  Modal,
  Form,
  InputNumber,
  Input,
  Tag,
  Table,
  Tabs,
  DatePicker,
  Drawer,
  Select,
  Image,
  Spin,
  Row,
  Col,
  message,
} from 'antd';
import { WalletOutlined, QrcodeOutlined } from '@ant-design/icons';
const { RangePicker } = DatePicker;

export default function Wallet() {
  // 模拟用户与钱包信息
  const [currencySymbol] = useState('¥');
  const [walletInfo, setWalletInfo] = useState({
    profitAmount: 320.25, // 可提现收益
    wallet: 1280.5,       // 账户余额
    printPoints: 560,      // 打印积分
    expireTime: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30).toISOString(), // 30天后
  });

  // 顶部操作：提现、购买套餐、CDK续费
  const [withDrawOpen, setWithDrawOpen] = useState(false);
  const [buyOpen, setBuyOpen] = useState(false);
  const [renewOpen, setRenewOpen] = useState(false);
  const [withDrawForm] = Form.useForm();
  const [renewForm] = Form.useForm();

  // 购买套餐：类型与套餐、二维码、支付状态
  const [nowOrderType, setNowOrderType] = useState(1); // 1 账户余额；2 点数
  const [packageArr, setPackageArr] = useState(() => (
    [
      { id: 1, payPrice: 50 },
      { id: 2, payPrice: 100 },
      { id: 3, payPrice: 200 },
      { id: 4, payPrice: 500 },
    ]
  ));
  const [rechargeInfo, setRechargeInfo] = useState(packageArr[0]);
  const [nowPayType, setNowPayType] = useState('WECHAT');
  const [codeInfo, setCodeInfo] = useState({ payCode: '' });
  const [payCodeStatus, setPayCodeStatus] = useState(0); // 0待支付 1成功 -1失败
  const [loadingCode, setLoadingCode] = useState(false);

  // 底部列表与搜索
  const [nowTab, setNowTab] = useState('receipt');
  const [searchDate, setSearchDate] = useState(null);
  const [searchInfo, setSearchInfo] = useState({ nickName: '', machineNo: '' });
  const receiptData = useMemo(() => (
    Array.from({ length: 8 }).map((_, i) => ({
      id: i + 1,
      nickName: `用户${i + 1}`,
      machineNo: `M-${1000 + i}`,
      payPrice: (Math.random() * 200 + 20).toFixed(2),
      createTime: `2025-01-${String((i % 28) + 1).padStart(2, '0')} 10:00:00`,
      payTime: `2025-01-${String((i % 28) + 1).padStart(2, '0')} 10:30:00`,
      orderType: 1,
      orderItems: [{ id: 1, goodsType: 1, goodsNum: 1, payPrice: 20 }],
    }))
  ), []);
  const pointData = useMemo(() => (
    Array.from({ length: 8 }).map((_, i) => ({
      id: i + 101,
      nickName: `用户${i + 1}`,
      machineNo: `M-${2000 + i}`,
      printPoints: Math.floor(Math.random() * 50 + 10),
      createTime: `2025-01-${String((i % 28) + 1).padStart(2, '0')} 15:00:00`,
    }))
  ), []);

  const receiptColumns = [
    { title: '订单号', dataIndex: 'id', width: 80 },
    { title: '昵称', dataIndex: 'nickName', width: 120 },
    { title: '设备号', dataIndex: 'machineNo', width: 140 },
    { title: '金额', dataIndex: 'payPrice', width: 100 },
    { title: '创建时间', dataIndex: 'createTime', width: 160 },
    { title: '支付时间', dataIndex: 'payTime', width: 160 },
    {
      title: '操作', dataIndex: 'actions', width: 120, fixed: 'right', render: (_, row) => (
        <Button type="primary" size="small" onClick={() => openDetail(row)}>详情</Button>
      )
    },
  ];
  const pointColumns = [
    { title: '记录号', dataIndex: 'id', width: 80 },
    { title: '昵称', dataIndex: 'nickName', width: 120 },
    { title: '设备号', dataIndex: 'machineNo', width: 120 },
    { title: '积分', dataIndex: 'printPoints', width: 80 },
    { title: '时间', dataIndex: 'createTime', width: 160 },
  ];

  // 详情抽屉
  const [detailOpen, setDetailOpen] = useState(false);
  const [detailData, setDetailData] = useState(null);
  const openDetail = (row) => { setDetailData(row); setDetailOpen(true); };

  // 触发提现
  const handlerOpenWithdraw = () => {
    withDrawForm.setFieldsValue({ amount: undefined });
    setWithDrawOpen(true);
  };
  const doWithdraw = async () => {
    const v = await withDrawForm.validateFields().catch(() => null);
    if (!v) return false;
    if (v.amount > walletInfo.profitAmount) {
      message.warning('提现金额不能超过可提现余额');
      return false;
    }
    setWalletInfo(prev => ({ ...prev, profitAmount: Number((prev.profitAmount - v.amount).toFixed(2)) }));
    message.success('提现申请已提交');
    setWithDrawOpen(false);
  };

  // 触发购买套餐（余额/积分）
  const handlerBuyPackage = (type) => {
    setNowOrderType(type);
    setRechargeInfo(packageArr[0]);
    setNowPayType('WECHAT');
    setCodeInfo({ payCode: '' });
    setPayCodeStatus(0);
    setBuyOpen(true);
    requestPayCode();
  };
  const requestPayCode = () => {
    setLoadingCode(true);
    // 使用占位二维码（避免外部请求失败）
    setTimeout(() => {
      setCodeInfo({ payCode: 'https://oss.reyeah.com/reyeah/20240328/1711594443337-4053dc61-0092-4f93-8c20-8b6bfc855ebd.png' });
      setLoadingCode(false);
      // 模拟轮询支付状态
      setTimeout(() => setPayCodeStatus(1), 2000);
    }, 800);
  };

  // 续费（CDK）
  const doRenew = async () => {
    const v = await renewForm.validateFields().catch(() => null);
    if (!v) return false;
    message.success('续费成功');
    setRenewOpen(false);
  };

  // 搜索过滤（示意）
  const filterList = (list) => {
    return list.filter((item) => {
      const byNick = searchInfo.nickName ? String(item.nickName).includes(searchInfo.nickName) : true;
      const byMachine = searchInfo.machineNo ? String(item.machineNo).includes(searchInfo.machineNo) : true;
      // 简单日期过滤示意（基于字符串）
      return byNick && byMachine;
    });
  };

  return (
    <div style={{ padding: 16 }}>
      {/* 顶部三卡片 */}
      <Row gutter={[24, 24]}>
        <Col xs={24} md={8}>
          <Card title="可提现金额" extra={<span style={{ color: 'var(--primary)' }}>{currencySymbol}</span>}>
            <Statistic value={walletInfo.profitAmount} precision={2} valueStyle={{ color: 'var(--primary)' }} />
            <div style={{ textAlign: 'right', marginTop: 12 }}>
              <Button type="primary" ghost onClick={handlerOpenWithdraw}>提现</Button>
            </div>
          </Card>
        </Col>
        <Col xs={24} md={8}>
          <Card title="账户余额" extra={<span style={{ color: 'var(--primary)' }}>{currencySymbol}</span>}>
            <Statistic value={walletInfo.wallet} precision={2} valueStyle={{ color: 'var(--primary)' }} />
            <div style={{ textAlign: 'right', marginTop: 12 }}>
              <Button type="primary" onClick={() => handlerBuyPackage(1)}>购买余额套餐</Button>
            </div>
          </Card>
        </Col>
        <Col xs={24} md={8}>
          <Card title="打印积分">
            <Space style={{ width: '100%', justifyContent: 'space-between' }}>
              <Statistic title="积分" value={walletInfo.printPoints} valueStyle={{ color: 'var(--primary)' }} />
              {walletInfo.expireTime && (
                <Statistic title="到期" valueRender={() => <span style={{ color: 'var(--primary)' }}>{new Date(walletInfo.expireTime).toLocaleDateString()}</span>} />
              )}
            </Space>
            <div style={{ textAlign: 'right', marginTop: 12 }}>
              <Space>
                <Button type="primary" onClick={() => handlerBuyPackage(2)}>购买积分套餐</Button>
                <Button type="primary" ghost onClick={() => setRenewOpen(true)}>CDK续费</Button>
              </Space>
            </div>
          </Card>
        </Col>
      </Row>

      {/* 底部 tabs 与列表 */}
      <Card style={{ marginTop: 16 }}>
        <div style={{ marginBottom: 10, display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
          <Input
            placeholder="昵称"
            style={{ width: 160 }}
            value={searchInfo.nickName}
            onChange={(e) => setSearchInfo(s => ({ ...s, nickName: e.target.value }))}
          />
          <Input
            placeholder="设备号"
            style={{ width: 160 }}
            value={searchInfo.machineNo}
            onChange={(e) => setSearchInfo(s => ({ ...s, machineNo: e.target.value }))}
          />
          <RangePicker showTime onChange={setSearchDate} style={{ width: 360 }} />
          <Button type="primary" onClick={() => message.info('已应用筛选')}>搜索</Button>
        </div>
        <Tabs
          activeKey={nowTab}
          onChange={setNowTab}
          animated
          items={[
            {
              key: 'receipt',
              label: '收款记录',
              children: (
                <Table rowKey="id" dataSource={filterList(receiptData)} columns={receiptColumns} pagination={{ pageSize: 8 }} scroll={{ x: 1000 }} />
              )
            },
            {
              key: 'point',
              label: '积分记录',
              children: (
                <Table rowKey="id" dataSource={filterList(pointData)} columns={pointColumns} pagination={{ pageSize: 8 }} scroll={{ x: 800 }} />
              )
            }
          ]}
        />
      </Card>

      {/* 提现弹窗 */}
      <Modal
        title="提现"
        open={withDrawOpen}
        onCancel={() => setWithDrawOpen(false)}
        onOk={doWithdraw}
        okText="确定"
        cancelText="取消"
        destroyOnHidden
      >
        <Form form={withDrawForm} layout="inline">
          <Form.Item name="amount" label="提现金额" rules={[{ required: true, message: '请选择提现金额' }]}> 
            <Select
              placeholder="选择金额"
              style={{ minWidth: 160 }}
              options={[50, 100, 500, 1000, 2000, 3000].map(v => ({ label: String(v), value: v }))}
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 购买套餐弹窗 */}
      <Modal
        title={nowOrderType === 1 ? '购买余额套餐' : '购买积分套餐'}
        open={buyOpen}
        onCancel={() => setBuyOpen(false)}
        onOk={() => { message.success('已完成购买'); setBuyOpen(false); }}
        okText="完成"
        destroyOnHidden
        width={820}
      >
        <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-evenly', gap: 12 }}>
          {packageArr.map(item => (
            <div key={item.id} style={{ position: 'relative' }}>
              <div
                onClick={() => setRechargeInfo(item)}
                style={{
                  height: 110,
                  width: 130,
                  borderRadius: 6,
                  background: '#fba94c',
                  color: '#fff',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: 24,
                  cursor: 'pointer',
                  boxShadow: '0 6px 16px rgba(0,0,0,0.15)'
                }}
              >
                {(nowOrderType === 1 ? '¥' : '') + item.payPrice + (nowOrderType === 2 ? '分' : '')}
              </div>
              {rechargeInfo?.id === item.id && (
                <div style={{ position: 'absolute', inset: 0, borderRadius: 6, boxShadow: '0 0 0 3px var(--primary)' }} />
              )}
            </div>
          ))}
        </div>
        <div style={{ margin: '12px 0' }} />
        <Tabs
          activeKey={nowPayType}
          onChange={setNowPayType}
          type="card"
          items={[
            {
              key: 'WECHAT',
              label: '微信支付',
              children: (
                <>
                  <div style={{ height: 220, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
                    <Spin spinning={loadingCode}>
                      <Image width={200} src={codeInfo.payCode} placeholder={<div style={{ width: 200, height: 200, background: '#fafafa' }} />} />
                      {payCodeStatus === 1 && (
                        <Tag color="success" style={{ position: 'absolute', top: 8, right: 8 }}>支付成功</Tag>
                      )}
                      {payCodeStatus === -1 && (
                        <Tag color="error" style={{ position: 'absolute', top: 8, right: 8 }}>支付失败</Tag>
                      )}
                    </Spin>
                  </div>
                  <div style={{ textAlign: 'center' }}>请使用微信扫码支付</div>
                </>
              )
            },
            {
              key: 'ALIPAY',
              label: '支付宝支付',
              children: (
                <>
                  <div style={{ height: 220, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
                    <Spin spinning={loadingCode}>
                      <Image width={200} src={codeInfo.payCode} placeholder={<div style={{ width: 200, height: 200, background: '#fafafa' }} />} />
                      {payCodeStatus === 1 && (
                        <Tag color="success" style={{ position: 'absolute', top: 8, right: 8 }}>支付成功</Tag>
                      )}
                      {payCodeStatus === -1 && (
                        <Tag color="error" style={{ position: 'absolute', top: 8, right: 8 }}>支付失败</Tag>
                      )}
                    </Spin>
                  </div>
                  <div style={{ textAlign: 'center' }}>请使用支付宝扫码支付</div>
                </>
              )
            },
            {
              key: 'PAYPAL',
              label: (<span><QrcodeOutlined /> PayPal</span>),
              children: (
                <>
                  <div style={{ height: 220, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
                    <Spin spinning={loadingCode}>
                      <Image width={200} src={codeInfo.payCode} placeholder={<div style={{ width: 200, height: 200, background: '#fafafa' }} />} />
                      {payCodeStatus === 1 && (
                        <Tag color="success" style={{ position: 'absolute', top: 8, right: 8 }}>支付成功</Tag>
                      )}
                      {payCodeStatus === -1 && (
                        <Tag color="error" style={{ position: 'absolute', top: 8, right: 8 }}>支付失败</Tag>
                      )}
                    </Spin>
                  </div>
                  <div style={{ textAlign: 'center' }}>PayPal 支付二维码示意</div>
                </>
              )
            }
          ]}
        />
      </Modal>

      {/* CDK续费 */}
      <Modal
        title="CDK续费"
        open={renewOpen}
        onCancel={() => setRenewOpen(false)}
        onOk={doRenew}
        okText="确定"
        destroyOnHidden
        width={520}
      >
        <Form form={renewForm} layout="vertical">
          <Form.Item name="cardNo" label="卡号" rules={[{ required: true, message: '请输入卡号' }]}> 
            <Input placeholder="请输入CDK卡号" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 详情抽屉 */}
      <Drawer open={detailOpen} onClose={() => setDetailOpen(false)} width={520} title="订单详情">
        {detailData && (
          <div>
            <Row gutter={12}>
              <Col span={12}>
                <Statistic title="类型" value={detailData.orderType === 1 ? '余额' : '积分'} />
              </Col>
              <Col span={12}>
                <Statistic title="金额" value={detailData.payPrice} />
              </Col>
            </Row>
            <div style={{ marginTop: 16 }}>
              <Table
                size="small"
                pagination={false}
                rowKey={(r) => r.id}
                columns={[
                  { title: '类型', dataIndex: 'goodsType' },
                  { title: '数量', dataIndex: 'goodsNum' },
                  { title: '金额', dataIndex: 'payPrice' },
                ]}
                dataSource={detailData.orderItems || []}
              />
            </div>
            <div style={{ marginTop: 12 }}>
              <Tag color="success" style={{ marginRight: 8 }}>订单 {detailData.id}</Tag>
              <Tag>设备 {detailData.machineNo}</Tag>
            </div>
          </div>
        )}
      </Drawer>
    </div>
  );
}